package com.x.share.mid.utils;

import java.util.HashMap;
import java.util.Map;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.x.share.mid.http.client.DefaultHttpClient;
import com.x.share.mid.prop.WxProperties;

public class WxTokenUtils {

	static Logger logger = LoggerFactory.getLogger(WxTokenUtils.class);

	static Map<String, JSONObject> cache = new HashMap<String, JSONObject>();

	public static String getWxAccessToken(WxProperties props) {
		String atkey = String.format("accessToken-%s", props.getAppId());
		JSONObject json = cache.get(atkey);
		if (json == null || new DateTime(json.getLong("wxATCreateTime")).plusMinutes(20).isBeforeNow()) {
			String url = String.format(
					"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=%s&secret=%s",
					props.getAppId(), props.getAppKey());
			JSONObject rlt = JSON.parseObject(DefaultHttpClient.get(url));
			logger.info(">>>> invoke wx access token: {} - {}", url, rlt.toJSONString());
			JSONObject data = new JSONObject();
			String accessToken = rlt.getString("access_token");
			data.put("wxAccessToken", accessToken);
			data.put("wxATCreateTime", System.currentTimeMillis());
			cache.put(atkey, data);
			return accessToken;
		} else {
			return json.getString("wxAccessToken");
		}
	}
	
	public static String getWxJsApiTicket(WxProperties props) {
		String jtkey = String.format("jsTicket-%s", props.getAppId());
		JSONObject json = cache.get(jtkey);
		if (json == null || new DateTime(json.getLong("wxJTCreateTime")).plusMinutes(20).isBeforeNow()) {
			String url = String.format(
					"https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi",
					getWxAccessToken(props));
			JSONObject rlt = JSON.parseObject(DefaultHttpClient.get(url));
			logger.info(">>>> invoke wx js ticket: {} - {}", url, rlt.toJSONString());
			JSONObject data = new JSONObject();
			String ticket = rlt.getString("ticket");
			data.put("wxJTicket", ticket);
			data.put("wxJTCreateTime", System.currentTimeMillis());
			cache.put(jtkey, data);
			return ticket;
		} else {
			return json.getString("wxJTicket");
		}
	}
	
	public static void clearCache() {
		cache.clear();
	}
}